package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import splug.cjk.packet.BBSCarPoolPacket;
import splug.cjk.packet.MessagePacket;

public class MessageRead extends Thread {

	private InputStream is;
	private OutputStream os;
	private ArrayList<Content> content = new ArrayList<Content>();
	private ArrayList<MessageContent> sub_content = new ArrayList<MessageContent>();
	
	
	public MessageRead(InputStream is, OutputStream os) {
		super();
		this.is = is;
		this.os = os;
	}


	@Override
	public void run() {
		super.run();
		try {
			/**
			 * 요청한 사람의 ID를 받아온다
			 */
			ObjectInputStream input = new ObjectInputStream(is);
			MessagePacket packet = (MessagePacket) input.readObject();
			String id = packet.getId();			
			
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/carpool?useUnicode=true&characterEncoding=euckr","root","apmsetup");
			Statement stmt = conn.createStatement();

			String query = "select f,comment,date from message where t = '" + id + "' order by number desc";

			stmt.execute("SET CHARACTER SET euckr");
			stmt.execute("set names euckr");

			ResultSet rs1 = stmt.executeQuery(query);			

			while(rs1.next()){
				String str1 = rs1.getString("f");
				String str2 = rs1.getString("comment");
				String str3 = rs1.getString("date");
				
				Content c = new Content(str2, str1);
				content.add(c);
				
				MessageContent m = new MessageContent(str2, str1, str3);
				sub_content.add(m);
			}
			
			packet = new MessagePacket(0, null, null, content, sub_content, null, null);
			ObjectOutputStream output = new ObjectOutputStream(os);
			output.writeObject(packet);
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
